package ltd.newbee.mall.product.controller;

import ltd.newbee.mall.product.entity.Product;
import ltd.newbee.mall.product.service.ProductService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping
public class ProductController {

    @Resource
    private ProductService productService;

    // API: 列表与详情
    @GetMapping("/api/products/{id}")
    @ResponseBody
    public Product detail(@PathVariable("id") Long id) {
        return productService.findById(id);
    }

    @GetMapping("/api/products")
    @ResponseBody
    public List<Product> page(@RequestParam(defaultValue = "1") int page,
                              @RequestParam(defaultValue = "10") int size,
                              @RequestParam(required = false) String keyword) {
        return productService.findPage(page, size, keyword);
    }

    // 页面：首页/详情/购物车/下单/登录
    @GetMapping({"/", "/index"})
    public String index(@RequestParam(defaultValue = "1") int page,
                        @RequestParam(defaultValue = "10") int size,
                        Model model) {
        List<Product> products = productService.findPage(page, size, null);
        model.addAttribute("hot", productService.findHot(8));
        model.addAttribute("news", productService.findNew(8));
        model.addAttribute("reco", productService.findRecommend(8));
        model.addAttribute("products", products);
        return "index";
    }

    @GetMapping("/search")
    public String search(@RequestParam(required = false) String keyword,
                         @RequestParam(defaultValue = "1") int page,
                         @RequestParam(defaultValue = "10") int size,
                         Model model) {
        List<Product> products = productService.findPage(page, size, keyword);
        model.addAttribute("products", products);
        model.addAttribute("keyword", keyword == null ? "" : keyword);
        return "search";
    }

    @GetMapping("/product/{id}")
    public String productPage(@PathVariable("id") Long id, Model model) {
        Product product = productService.findById(id);
        model.addAttribute("product", product);
        return "product-detail";
    }

    @GetMapping("/cart")
    public String cartPage() { return "cart"; }

    @GetMapping("/order/confirm")
    public String orderConfirmPage() { return "order-confirm"; }

    @GetMapping("/login")
    public String loginPage() { return "login"; }
}


